/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.Seguridad;

import Controlador.Bean.Seguridad.Perfil;
import Controlador.Service.Seguridad.ServicioPerfil;
import java.util.List;
import java.awt.Checkbox;
import java.awt.Dimension;
import java.awt.Font;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import javax.swing.GroupLayout;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.event.InternalFrameEvent;

/**
 *
 * @author MI PC
 */
public class AgregarEditarPerfil extends javax.swing.JInternalFrame {

    /**
     * Creates new form AgregarEditarPerfil
     */
    Perfil antiguo;
    HashMap<String,List<String>> Permisosagregar= new HashMap<>();
    HashMap<String,List<String>> PermisosRemover=new HashMap<>();
    HashMap<String,List<String>> PermisosActuales=new HashMap<>();
    HashMap<String,String> PermisosActualesA=new HashMap<>();
    HashMap<String,String> PermisosActualesR=new HashMap<>();
    BuscarPerfil vnt=null;
    int sel=0;
    ArrayList <javax.swing.JCheckBox> listaCheckbox;
    //AgregarEditarPerfil vntthis=null;
    
    public AgregarEditarPerfil(String codigo,BuscarPerfil vnt) {
        initComponents();
        this.vnt=vnt;
        //vntthis=this;               
        listaCheckbox= new ArrayList<>();
        List <HashMap<String,Object>> permisos=null;
        if(codigo!=null && !codigo.isEmpty()){
            Perfil temporal=new Perfil();
            temporal.setIdPerfil(codigo);
            antiguo=(Perfil)(new ServicioPerfil().seleccionarXCriterios(temporal).get(0));  
            txtCodigo.setText(antiguo.getIdPerfil());
            txtNombres.setText(antiguo.getNombre());
            txtDescripcion.setText(antiguo.getDescripcion());
            permisos=new ServicioPerfil().obtenerPermisos(codigo);
            this.title="Editar Perfil";
        }
        else 
        {antiguo=null;
        permisos= new ServicioPerfil().obtenerPermisos(null);
        this.title="Agregar Perfil";
                }
        
        javax.swing.GroupLayout panelPermisosLayout = new javax.swing.GroupLayout(panelPermisos);
        panelPermisos.setLayout(panelPermisosLayout);
        //panelPermisosLayout.setAutoCreateGaps(true);
        //panelPermisosLayout.setAutoCreateContainerGaps(true);
        GroupLayout.SequentialGroup layoutV=panelPermisosLayout.createSequentialGroup();
        GroupLayout.SequentialGroup layoutHContainer=panelPermisosLayout.createSequentialGroup();
        GroupLayout.ParallelGroup layoutH=panelPermisosLayout.createParallelGroup();
      // GroupLayout.SequentialGroup HorizontalLineH=panelPermisosLayout.createSequentialGroup();
        //GroupLayout.ParallelGroup HorizontalLineV=panelPermisosLayout.createParallelGroup(GroupLayout.Alignment.BASELINE);
        
        //int contador=0;        
        //String titulo=null;
        //layoutHContainer=layoutHContainer.addGap(20, 20, 20);
        String modulo=null;
        javax.swing.JLabel label= new javax.swing.JLabel();
        int contador=0;
        for(int i=0;i<permisos.size();i++){      
            
            if(modulo==null || ((String)permisos.get(i).get("modulo")).compareTo(modulo)!=0){                
                label= new javax.swing.JLabel();
                label.setText(((String)permisos.get(i).get("modulo")));                
                Font font = label.getFont();
                Font boldFont = new Font(font.getFontName(), Font.BOLD, font.getSize());
                label.setFont(boldFont);
                layoutH=layoutH.addComponent(label);
                layoutV=layoutV.addComponent(label);
                modulo=((String)permisos.get(i).get("modulo"));
                contador++;
            }
            
            javax.swing.JCheckBox temp = new javax.swing.JCheckBox();  
            if(Integer.valueOf(((String)permisos.get(i).get("indicador"))).equals(1)) temp.setSelected(true);
            temp.setName(((String)permisos.get(i).get("permiso")));
            temp.setText((String)permisos.get(i).get("casouso"));            
            temp.setVisible(true);
            temp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                generalCheckboxAction(evt);
            }
            });
            listaCheckbox.add(temp);           
             layoutH=layoutH.addComponent(listaCheckbox.get(i));
             layoutV=layoutV.addComponent(listaCheckbox.get(i));
             contador++;
            if(!Integer.valueOf(((String)permisos.get(i).get("indicador"))).equals(-1)) PermisosActuales.put((String)(permisos.get(i).get("permiso")),Arrays.asList(((String)(permisos.get(i).get("permiso"))).split("\\.")));
           
        }
        Dimension size=panelPermisos.getSize();
        size.height=20*contador;
        panelPermisos.setSize(size);
        size=panelPrueba.getSize();
        size.height=20*contador;
        panelPrueba.setSize(size);
        /*if(contador>0 && contador%5!=0) {
                layoutH=layoutH.addGroup(HorizontalLineH);
                layoutV=layoutV.addGroup(HorizontalLineV);
                layoutV=layoutV.addGap(4, 4, 4);
                HorizontalLineH=panelPermisosLayout.createSequentialGroup();
                HorizontalLineV=panelPermisosLayout.createParallelGroup();
            }*/
        layoutHContainer=layoutHContainer.addGroup(layoutH);
        layoutHContainer=layoutHContainer.addContainerGap(405, Short.MAX_VALUE);
         panelPermisosLayout.setHorizontalGroup(
            panelPermisosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layoutHContainer));
        panelPermisosLayout.setVerticalGroup(
            panelPermisosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layoutV));
        panelPermisos.revalidate();
        panelPermisos.repaint();

    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane3 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jPopupMenu1 = new javax.swing.JPopupMenu();
        jScrollPane1 = new javax.swing.JScrollPane();
        panelDatos = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtNombres = new javax.swing.JTextField();
        txtCodigo = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtDescripcion = new javax.swing.JTextArea();
        btnOperar = new javax.swing.JButton();
        btnSeleccionar = new javax.swing.JButton();
        panelPrueba = new javax.swing.JScrollPane();
        panelPermisos = new javax.swing.JPanel();

        jScrollPane3.setViewportView(jTree1);

        setClosable(true);
        setIconifiable(true);

        panelDatos.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del Perfil"));
        panelDatos.setToolTipText("");
        panelDatos.setName(""); // NOI18N

        jLabel1.setText("Codigo");

        jLabel2.setText("Nombres");

        txtCodigo.setEditable(false);
        txtCodigo.setMinimumSize(new java.awt.Dimension(127, 20));
        txtCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCodigoActionPerformed(evt);
            }
        });

        jLabel3.setText("Descripcion");

        txtDescripcion.setColumns(20);
        txtDescripcion.setLineWrap(true);
        txtDescripcion.setRows(3);
        txtDescripcion.setTabSize(0);
        jScrollPane2.setViewportView(txtDescripcion);

        javax.swing.GroupLayout panelDatosLayout = new javax.swing.GroupLayout(panelDatos);
        panelDatos.setLayout(panelDatosLayout);
        panelDatosLayout.setHorizontalGroup(
            panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDatosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(panelDatosLayout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtNombres, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelDatosLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(103, 103, 103)
                        .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelDatosLayout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelDatosLayout.setVerticalGroup(
            panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDatosLayout.createSequentialGroup()
                .addContainerGap(13, Short.MAX_VALUE)
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(17, 17, 17))
        );

        btnOperar.setText("Guardar");
        btnOperar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOperarActionPerformed(evt);
            }
        });

        btnSeleccionar.setText("Seleccionar Todo");
        btnSeleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionarActionPerformed(evt);
            }
        });

        panelPermisos.setBorder(javax.swing.BorderFactory.createTitledBorder("Permisos del Perfil"));
        panelPermisos.setMaximumSize(new java.awt.Dimension(486, 1000));
        panelPermisos.setPreferredSize(new java.awt.Dimension(300, 700));
        panelPermisos.setRequestFocusEnabled(false);

        javax.swing.GroupLayout panelPermisosLayout = new javax.swing.GroupLayout(panelPermisos);
        panelPermisos.setLayout(panelPermisosLayout);
        panelPermisosLayout.setHorizontalGroup(
            panelPermisosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 314, Short.MAX_VALUE)
        );
        panelPermisosLayout.setVerticalGroup(
            panelPermisosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 677, Short.MAX_VALUE)
        );

        panelPrueba.setViewportView(panelPermisos);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(btnOperar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnSeleccionar)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(panelDatos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(panelPrueba, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 345, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelDatos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnOperar)
                    .addComponent(btnSeleccionar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelPrueba, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
                .addContainerGap())
        );

        panelDatos.getAccessibleContext().setAccessibleName("Datos del Peril");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodigoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoActionPerformed

    private void btnSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionarActionPerformed
            if(sel==1) {
                this.btnSeleccionar.setText("Seleccionar todos");
                sel=0;
                for(int i=0;i<this.listaCheckbox.size();i++){
                    if(this.listaCheckbox.get(i).isSelected())this.listaCheckbox.get(i).doClick(); 
                }
            }
            else{
                this.btnSeleccionar.setText("Deseleccionar todos");
                sel=1;
                for(int i=0;i<this.listaCheckbox.size();i++){
                    if(!this.listaCheckbox.get(i).isSelected())this.listaCheckbox.get(i).doClick();    
                }
            }
        
    }//GEN-LAST:event_btnSeleccionarActionPerformed

    private void generalCheckboxAction(java.awt.event.ActionEvent evt){
        javax.swing.JCheckBox checkbox=(javax.swing.JCheckBox)evt.getSource();        
          //JOptionPane.showMessageDialog(this, checkbox.getName());
        List<String> temporal=Arrays.asList(checkbox.getName().split("\\."));        
        boolean actual=PermisosActuales.get(checkbox.getName())!=null;
        if(checkbox.isSelected()) {
            if(actual){
                if(PermisosActualesR.get(checkbox.getName())!=null){
                    PermisosActualesR.remove(checkbox.getName());
                }
                else PermisosActualesA.put(checkbox.getName(),checkbox.getName());                    
            
            }
            else{                        
                if(PermisosRemover.get(checkbox.getName())!=null){
                    PermisosRemover.remove(checkbox.getName());
                }
                else Permisosagregar.put(checkbox.getName(),temporal);                    
            }
        }
        else{
            if(actual){
                if(PermisosActualesA.get(checkbox.getName())!=null){
                    PermisosActualesA.remove(checkbox.getName());
                }
                else PermisosActualesR.put(checkbox.getName(),checkbox.getName());        
            }
            else{
                if(Permisosagregar.get(checkbox.getName())!=null){
                    Permisosagregar.remove(checkbox.getName());
                }
                else PermisosRemover.put(checkbox.getName(),temporal);        
            }
        }
    }
    
    private void btnOperarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOperarActionPerformed
        Object[] options = {"Si", "No"};
        int n = JOptionPane.showOptionDialog(this, "¿Desea guardar los cambios realizados?", "Confirmar", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
        if (n == 0) {

            if (!txtNombres.getText().isEmpty()) {
                Perfil perfil = new Perfil();
                perfil.setIdPerfil(txtCodigo.getText());
                perfil.setNombre(txtNombres.getText());
                perfil.setDescripcion(txtDescripcion.getText());
                if (perfil.getNombre() != null && perfil.getDescripcion() != null) {
                    if (antiguo == null) {
                        new ServicioPerfil().Guardar(perfil, Permisosagregar, PermisosRemover, PermisosActualesA, PermisosActualesR);
                    } else {
                        new ServicioPerfil().Actualizar(perfil, Permisosagregar, PermisosRemover, PermisosActualesA, PermisosActualesR);
                    }
                    vnt.actualizarTabla();
                    this.dispose();
                }
            }
            
            else{
                JOptionPane.showMessageDialog(null, "El nombre no debe estar vacío"  );
            }
        }
    }//GEN-LAST:event_btnOperarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnOperar;
    private javax.swing.JButton btnSeleccionar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTree jTree1;
    private javax.swing.JPanel panelDatos;
    private javax.swing.JPanel panelPermisos;
    private javax.swing.JScrollPane panelPrueba;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextArea txtDescripcion;
    private javax.swing.JTextField txtNombres;
    // End of variables declaration//GEN-END:variables
}
